const jwt = require('koa-jwt');
const Router = require('koa-router');
const router = new Router({prefix:'/users'});
const { find, findById, create, update, delete:del, login, checkOwner,
     listFollowing, checkUserExist, follow, unfollow, listFollowers, listFollowingTopics,
     followTopic, unfollowTopic, listQuestions,
     listLikingAnswers, likeAnswer, unlikeAnswer,
     listDislikingAnswers, dislikeAnswer, undislikeAnswer,
     listCollectingAnswers, collectAnswer, uncollectAnswer} = require('../controllers/users');

const { checkTopicExist } = require('../controllers/topics'); //引入话题是否存在
const { checkAnswerExist } = require('../controllers/answers');//验证答案是否存在中间件
const { secret } = require('../config');
//登录jwt验证
const auth = jwt({ secret });
// const auth = async(ctx, next) => {
//     const { authorization = '' } = ctx.request.header;
//     const token = authorization.replace('Bearer ', '');
//     try {
//         const user = jsonwebtoken.verify(token, secret);
//         ctx.state.user = user;
//     } catch (err) {
//         ctx.throw(401, err.message);
//     }
//     await next();
// }

router.get('/', find);//获取所有数据
router.post('/', create);//创建数据
router.get('/:id', findById);//获取指定数据
router.patch('/:id', auth, checkOwner, update);//更新数据
router.delete('/:id', auth, checkOwner, del);//删除数据
router.post('/login', login);//用户登录
router.get('/:id/following', listFollowing);//获取关注人列表
router.get('/:id/followers', listFollowers);//获取某个用户的粉丝列表
router.put('/following/:id', auth, checkUserExist, follow);//关注某人
router.delete('/following/:id', auth, checkUserExist, unfollow);//取消关注
router.put('/followingTopics/:id', auth, checkTopicExist, followTopic);//关注话题
router.delete('/followingTopics/:id', auth, checkTopicExist, unfollowTopic);//取消关注话题
router.get('/:id/followingTopics', listFollowingTopics);//获取某个用户关注的话题列表
router.get('/:id/questions', listQuestions);//问题列表
router.get('/:id/likingAnswers', listLikingAnswers);//喜欢的答案列表
router.put('/likingAnswers/:id', auth, checkAnswerExist, likeAnswer, undislikeAnswer);//指定喜欢的答案点赞
router.delete('/likingAnswers/:id', auth, checkAnswerExist, unlikeAnswer);//删除喜欢的答案
router.get('/:id/dislikingAnswers', listDislikingAnswers);//踩过的答案列表
router.put('/dislikingAnswers/:id', auth, checkAnswerExist, dislikeAnswer, unlikeAnswer);//指定踩过的答案
router.delete('/dislikingAnswers/:id', auth, checkAnswerExist, undislikeAnswer);//删除踩过的答案
router.get('/:id/collectingAnswers', listCollectingAnswers);//列出收藏的答案
router.put('/collectingAnswers/:id', auth, checkAnswerExist, collectAnswer);//收藏答案
router.delete('/collectingAnswers/:id', auth, checkAnswerExist, uncollectAnswer);//取消收藏答案

module.exports = router;